package ink.metoo.gude.module.security.service.impl

import ink.metoo.gude.module.security.domain.SimpleUserDetails
import ink.metoo.gude.module.security.repository.UserRepository
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class UserDetailsServiceImpl(
    private val userRepository: UserRepository
) : UserDetailsService {

    @Transactional
    override fun loadUserByUsername(username: String?): UserDetails {
        if (username.isNullOrBlank()) {
            throw UsernameNotFoundException("username must not be null")
        }
        val user = userRepository.findByEmail(username) ?: throw UsernameNotFoundException("user $username not found")
        return SimpleUserDetails(user)
    }

}